import torch
import torch.nn as nn
import torch.optim as optim
import scipy.io
import matplotlib.pyplot as plt
import numpy as np
import os

# 设置参数 只考虑时间
m = 50  # 时间步数，即数据在时间维度上的长度。这里的m代表有6个时间点
k = 481   # 丰度矩阵的维度，即端元个数
K_nonzero = 20  # 稀疏性要求，即在表示向量X中，每个时间步选择前20个值为非零，其余为零
lambda_sparsity = 0.1  # 稀疏正则化系数，用于控制稀疏性损失在总损失中的权重
epochs = 1000   # 训练的迭代次数
learning_rate = 0.001  # 优化器的学习率

# 数据读取参数
data_folder1 = "dync"
file_prefix = "spatial_correlation_"
file_extension = ".mat"

# 数据读取与预处理部分（保持和原代码一致，此处省略详细注释，可参考原代码解释）
result_matrix = np.zeros((8, 8, m), dtype=np.complex64)
for i in range(1, m + 1):
    fname2 = os.path.join(data_folder1, f"{file_prefix}{i}{file_extension}")
    if os.path.exists(fname2):
        mat2 = scipy.io.loadmat(fname2)
        if "p" in mat2:
            Y = mat2["p"]
            if Y.size == 64:
                Y_reshaped = Y.reshape(8, 8)
                result_matrix[:, :, i - 1] = Y_reshaped
            else:
                print(f"Shape of 'p' in {fname2} is not compatible for reshaping to 8x8.")
        else:
            print(f"'p' not found in {fname2}")
    else:
        print(f"File not found: {fname2}")

Y_real = np.real(result_matrix).reshape(64, m)
Y_imag = np.imag(result_matrix).reshape(64, m)
Y_combined = np.concatenate((Y_real, Y_imag), axis=0)
Y_tensor = torch.from_numpy(Y_combined).float().cuda().unsqueeze(0)

# 读取端元矩阵D（保持和原代码一致，此处省略详细注释，可参考原代码解释）
fname4 = "Data/DC1/phasecha.mat"
mat4 = scipy.io.loadmat(fname4)
D = mat4["phasecha"]
if D.shape[0] == 64:
    D_reshaped = D.reshape(64, k)
else:
    raise ValueError("The number of rows in D is not compatible with 8x8 reshaping.")

D_real = np.real(D_reshaped)
D_imag = np.imag(D_reshaped)
D_combined = np.concatenate((D_real, D_imag), axis=0)
D_tensor = torch.from_numpy(D_combined).float().cuda()

class CNNLSTMAutoencoder(nn.Module):
    def __init__(self, k, D, time_steps):
        super(CNNLSTMAutoencoder, self).__init__()
        # 编码器部分
        self.cnn = nn.Sequential(
            nn.Conv1d(128, 64, kernel_size=3, stride=1, padding=1),  # 保持时间步大小
            nn.ReLU(),
            nn.Conv1d(64, 32, kernel_size=3, stride=1, padding=1),   # 保持时间步大小
            nn.ReLU()
        )
        
        # LSTM部分
        self.lstm = nn.LSTM(input_size=32, hidden_size=16, num_layers=1, batch_first=True)
        
        # 全连接层映射到 k*m 的大小
        self.fc = nn.Sequential(
            nn.Linear(16 * time_steps, k * time_steps),  # LSTM输出展平后传递到全连接层
            nn.ReLU()
        )

        self.k = k
        self.time_steps = time_steps
        self.register_buffer('D', D)  # 注册端元矩阵为模型的buffer，避免训练时更新

    def forward(self, Y):
        # CNN部分 (batch, 128, m)
        Y_cnn = self.cnn(Y)  # (batch, 32, m)
        
        # 调整维度以适配LSTM输入 (batch, m, 32)
        Y_lstm_input = Y_cnn.transpose(1, 2)
        
        # LSTM部分
        Y_lstm_output, _ = self.lstm(Y_lstm_input)  # (batch, m, 16)
        
        # 展平并通过全连接层
        Y_flat = Y_lstm_output.reshape(Y_lstm_output.size(0), -1)  # (batch, 16 * m)
        X = self.fc(Y_flat)  # (batch, k * m)
        X = X.view(-1, self.k, self.time_steps)  # (batch, k, m)

        # 稀疏化：只保留每个时间步前 K_nonzero 个最大值
        topk_values, topk_indices = torch.topk(X, K_nonzero, dim=1)
        mask = torch.zeros_like(X)
        mask.scatter_(1, topk_indices, topk_values)
        X = mask

        # 归一化
        X = X / (torch.sum(X, dim=1, keepdim=True) + 1e-8)

        # 重构Y：D * X
        X_transposed = X.transpose(1, 2)  # (batch, m, k)
        Y_reconstructed = torch.einsum("bmk,ik->bmi", X_transposed, self.D)
        Y_reconstructed = Y_reconstructed.transpose(1, 2)  # (batch, 128, m)

        return Y_reconstructed, X
# 初始化模型、损失函数和优化器
model = CNNLSTMAutoencoder(k=k, D=D_tensor, time_steps=m).cuda()
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# 训练过程
loss_values = []
for epoch in range(epochs):
    model.train()
    optimizer.zero_grad()

    # 前向传播
    Y_reconstructed, X = model(Y_tensor)

    # MSE重构误差
    mse_loss = criterion(Y_reconstructed, Y_tensor)

    # 稀疏性损失
    target_sparsity = K_nonzero / k
    actual_sparsity = (X > 0).float().mean(dim=1)
    sparsity_loss = ((actual_sparsity - target_sparsity) ** 2).mean()

    # 总损失
    # loss = mse_loss + lambda_sparsity * sparsity_loss
    # 总损失
    loss = mse_loss 

    # 后向传播
    loss.backward()
    optimizer.step()

    loss_values.append(loss.item())

    # 打印日志
    if (epoch + 1) % 100 == 0:
        print(f"Epoch [{epoch + 1}/{epochs}], Total Loss: {loss.item():.4f}, "
              f"MSE Loss: {mse_loss.item():.4f}, Sparsity Loss: {sparsity_loss.item():.4f}")

# 绘制损失曲线
plt.plot(range(epochs), loss_values)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Loss Curve')
plt.show()

# 测试模型
model.eval()
with torch.no_grad():
    Y_reconstructed, X = model(Y_tensor)
mse_total = criterion(Y_reconstructed, Y_tensor).item()
print(f"Final Reconstruction MSE: {mse_total:.6f}")
# 计算最终重构误差
mse_total = criterion(Y_reconstructed, Y_tensor).item()
# 去掉批次维度，保留 [128, 50]，再取列
subset1 = Y_reconstructed.squeeze(0)[:, 1]  # 结果形状 [128, 1]
subset2=Y_tensor.squeeze(0)[:,1] # 结果形状 [128, 1]
mse_total1 = criterion(subset1 ,subset2).item()
rmse_total = torch.sqrt(torch.tensor(mse_total1)).item()
subset3 = Y_reconstructed.squeeze(0)  # 结果形状 [128, 1]
subset4=Y_tensor.squeeze(0)  # 结果形状 [128, 1]
# 逐列计算 RMSE

rmse_per_column = torch.sqrt(torch.mean((subset3 - subset4) ** 2, dim=0))
print("逐列 RMSE:", rmse_per_column)
print(f"Final Reconstruction MSE: {mse_total:.6f}")
